package com.zcx.controller;


import com.zcx.pojo.vo.JSONResult;
import com.zcx.service.FileService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    FileService fileService;

    @PostMapping("upload")
    public JSONResult upload(@RequestPart(value = "file") final MultipartFile uploadfile) throws IOException {

        String originalFilename = uploadfile.getOriginalFilename();
//        从前端传过来的对象名
        String name = uploadfile.getName();
        String contentType = uploadfile.getContentType();
        String extension = FilenameUtils.getExtension(originalFilename);
        long size = uploadfile.getSize();

        System.out.println(
                "文件的原始名："+originalFilename + "\n" +
                        "文件的名字为：" +name  + "\n" +
                        "文件的类型："+contentType + "\n" +
                        "文件的后缀为："+extension + "\n" +
                        "文件的大小为："+size + "\n"
        );

        String path = ResourceUtils.getURL("classpath:").getPath();
        System.out.println("resource路径为 ->"+ path);

        String completePath = path+"/static/file/"+originalFilename;
        FileUtils.copyToFile(uploadfile.getInputStream(),new File(completePath));

        return fileService.readFile(uploadfile,completePath);



    }

}
